<template>
  <div :id="echarts" :style="getheight" class="backtran"></div>
</template>
<script>
export default {
  name: 'bar',
  mixins: [],
  computed: {
    echarts() {
      return 'echarts' + Math.random() * 100000
    },
    getheight() {
      return `height:${this.height}px`
    }
  },
  props: {
    chartData: {
      type: Object,
      default: () => []
    },
    height: {
      type: Number,
      default: 340
    },
    title: {
      type: String,
      default: ''
    }
  },
  watch: {
    chartData() {
      this.draw()
    }
  },
  data() {
    return {
      list: [],
      option: {
        color: ['#45c946'],
        title: {
          text: this.title,
          textStyle: {
            fontSize: '18px',
            color: '#fff',
            fontWeight: 'normal'
          },
          top: '0',
          left: '0'
        },
        grid: { top: '0', left: '0', right: '0', bottom: '0' },
        legend: {
          orient: 'horizontal',
          left: 'center',
          top: 2,
          data: this.chartData.legend,
          textStyle: {
            fontSize: 12, //字体大小
            color: '#ffffff' //字体颜色
          }
        },
        tooltip: {
          trigger: 'axis'
        },

        yAxis: {
          type: 'value',
          data: [],
          show: false
        },
        xAxis: {
          splitNumber: 3,
          type: 'category',
          show: false
        },

        series: []
      }
    }
  },
  mounted() {
    this.draw()
  },
  methods: {
    draw() {
      const chartFactor = this.$echarts.init(
        document.getElementById(this.echarts)
      )
      window.onresize = chartFactor.resize
      let List = this.chartData.y
      let series = []
      let legends = this.chartData.legend
      let xData = this.chartData.x
      for (let i in List) {
        let serie = {
          type: 'bar',
          name: legends[i],
          data: List[i],
          barMinWidth: 5
        }
        series.push(serie)
      }

      this.option.xAxis.data = xData[0]
      this.option.series = series
      chartFactor.setOption(this.option)
    }
  }
}
</script>
<style lang="scss" scoped>
.backtran {
  background-color: transparent;
}
</style>